<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考试题目数据处理工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
            line-height: 1.6;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            opacity: 0.9;
            font-size: 1.1em;
        }

        .content {
            padding: 30px;
        }

        .section {
            margin-bottom: 30px;
            padding: 25px;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            background-color: #fafafa;
        }

        .section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.5em;
            display: flex;
            align-items: center;
        }

        .section h2::before {
            content: '';
            width: 4px;
            height: 24px;
            background: #667eea;
            margin-right: 10px;
            border-radius: 2px;
        }

        .input-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #555;
        }

        textarea, input[type="text"] {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        textarea:focus, input[type="text"]:focus {
            outline: none;
            border-color: #667eea;
        }

        textarea {
            min-height: 150px;
            resize: vertical;
            font-family: 'Consolas', 'Monaco', monospace;
        }

        .file-upload {
            position: relative;
            display: inline-block;
            cursor: pointer;
            width: 100%;
        }

        .file-upload input[type="file"] {
            position: absolute;
            opacity: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }

        .file-upload-label {
            display: block;
            padding: 15px;
            border: 2px dashed #667eea;
            border-radius: 6px;
            text-align: center;
            color: #667eea;
            transition: all 0.3s;
        }

        .file-upload:hover .file-upload-label {
            background-color: #f0f0ff;
            border-color: #764ba2;
        }

        .buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 20px;
        }

        button {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        .btn-success {
            background: linear-gradient(135deg, #2ecc71 0%, #27ae60 100%);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(46, 204, 113, 0.4);
        }

        .btn-warning {
            background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%);
            color: white;
        }

        .btn-warning:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(243, 156, 18, 0.4);
        }

        .btn-danger {
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
            color: white;
        }

        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(231, 76, 60, 0.4);
        }

        .output {
            margin-top: 20px;
            padding: 15px;
            border-radius: 8px;
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            max-height: 400px;
            overflow-y: auto;
        }

        .output.success {
            background-color: #d4edda;
            border-color: #c3e6cb;
            color: #155724;
        }

        .output.error {
            background-color: #f8d7da;
            border-color: #f5c6cb;
            color: #721c24;
        }

        .output.info {
            background-color: #d1ecf1;
            border-color: #bee5eb;
            color: #0c5460;
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin: 20px 0;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            text-align: center;
            border-left: 4px solid #667eea;
        }

        .stat-number {
            font-size: 2.5em;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 5px;
        }

        .stat-label {
            color: #666;
            font-size: 0.9em;
        }

        .preview-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
            font-size: 14px;
        }

        .preview-table th,
        .preview-table td {
            padding: 8px 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        .preview-table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }

        .preview-table tr:hover {
            background-color: #f5f5f5;
        }

        .file-list {
            margin-top: 15px;
        }

        .file-item {
            padding: 12px;
            margin: 8px 0;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 6px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.3s;
        }

        .file-item:hover {
            transform: translateX(5px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .file-item a {
            color: #667eea;
            text-decoration: none;
            font-weight: 600;
        }

        .file-item a:hover {
            text-decoration: underline;
        }

        .progress-bar {
            width: 100%;
            height: 6px;
            background-color: #e0e0e0;
            border-radius: 3px;
            overflow: hidden;
            margin: 10px 0;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea, #764ba2);
            transition: width 0.3s ease;
            border-radius: 3px;
        }

        .hidden {
            display: none;
        }

        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 6px;
            border: 1px solid transparent;
        }

        .alert-info {
            color: #0c5460;
            background-color: #d1ecf1;
            border-color: #bee5eb;
        }

        .alert-warning {
            color: #856404;
            background-color: #fff3cd;
            border-color: #ffeaa7;
        }

        .alert-success {
            color: #155724;
            background-color: #d4edda;
            border-color: #c3e6cb;
        }

        .alert-danger {
            color: #721c24;
            background-color: #f8d7da;
            border-color: #f5c6cb;
        }

        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 10px;
            }
            
            .content {
                padding: 20px;
            }
            
            .buttons {
                flex-direction: column;
            }
            
            button {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📊 考试题目数据处理工具</h1>
            <p>智能处理考试数据，支持CSV/XLSX格式，自动合并多行记录</p>
        </div>

        <div class="content">
            <!-- 数据导入区域 -->
            <div class="section">
                <h2>📥 数据导入</h2>
                
                <div class="input-group">
                    <label>方式1：粘贴CSV文本</label>
                    <textarea id="csvInput" placeholder="请将CSV格式的文本粘贴到这里..."></textarea>
                </div>

                <div class="input-group">
                    <label>方式2：上传文件</label>
                    <div class="file-upload">
                        <input type="file" id="fileInput" accept=".csv,.xlsx" />
                        <label class="file-upload-label">
                            📁 点击选择文件或拖拽文件到此处<br>
                            <small>支持 .csv 和 .xlsx 格式</small>
                        </label>
                    </div>
                </div>

                <div class="buttons">
                    <button class="btn-primary" onclick="loadData()">
                        <span id="loadBtnText">📊 加载数据</span>
                        <span id="loadSpinner" class="loading hidden"></span>
                    </button>
                    <button class="btn-warning" onclick="clearData()">🗑️ 清空数据</button>
                </div>

                <div id="loadStatus" class="output hidden"></div>
            </div>

            <!-- 数据预览区域 -->
            <div class="section hidden" id="previewSection">
                <h2>👀 数据预览</h2>
                <div id="dataStats" class="stats"></div>
                <div id="dataPreview" class="output"></div>
            </div>

            <!-- 数据筛选区域 -->
            <div class="section hidden" id="filterSection">
                <h2>🔍 数据筛选与导出</h2>
                
                <div class="input-group">
                    <label>自定义输出文件名（可选）</label>
                    <input type="text" id="customFilename" placeholder="留空使用默认文件名">
                </div>

                <!-- 筛选条件说明 -->
                <div class="alert alert-info">
                    <strong>📋 筛选条件说明：</strong>
                    <ul style="margin: 10px 0; padding-left: 20px;">
                        <li><strong>❓ 筛选未作答题目：</strong>当题目描述非空且回答情况为"未作答"时，输出文件名为"未作答题目.csv"</li>
                        <li><strong>❌ 筛选错误题目：</strong>当题目描述非空且回答情况为"错误"时，输出文件名为"错误题目.csv"</li>
                        <li><strong>⚠️ 筛选题干缺失且未作答：</strong>当题目描述为空且回答情况为"未作答"时，输出文件名为"干缺失且未作答.csv"</li>
                        <li><strong>🔴 筛选题干缺失且回答错误：</strong>当题目描述为空且回答情况为"错误"时，输出文件名为"干缺失且回答错误.csv"</li>
                    </ul>
                </div>

                <div class="buttons">
                    <button class="btn-success" onclick="filterData('unanswered')">
                        ❓ 筛选未作答题目
                    </button>
                    <button class="btn-danger" onclick="filterData('wrong')">
                        ❌ 筛选错误题目
                    </button>
                    <button class="btn-warning" onclick="filterData('missing_unanswered')">
                        ⚠️ 筛选题干缺失且未作答
                    </button>
                    <button class="btn-danger" onclick="filterData('missing_wrong')" style="background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);">
                        🔴 筛选题干缺失且回答错误
                    </button>
                </div>

                <!-- 实时筛选预览 -->
                <div id="filterPreview" style="margin: 20px 0; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                    <h4>📊 当前可筛选数据预览：</h4>
                    <div id="liveStats" style="display: flex; gap: 15px; flex-wrap: wrap; margin-top: 10px;">
                        <!-- 动态填充预览数据 -->
                    </div>
                </div>

                <div id="filterStatus" class="output hidden"></div>
                <div id="downloadLinks" class="file-list"></div>
            </div>

            <!-- Markdown格式导出区域 -->
            <div class="section hidden" id="markdownSection">
                <h2>📝 Markdown格式导出</h2>
                
                <div class="alert alert-info">
                    <strong>📋 Markdown格式说明：</strong>
                    <ul style="margin: 10px 0; padding-left: 20px;">
                        <li><strong>题目格式：</strong>使用三级标题(###)显示题目描述</li>
                        <li><strong>选项格式：</strong>每个选项单独一行，以"- "开头</li>
                        <li><strong>答题信息：</strong>包含回答情况、正确答案、你的答案</li>
                        <li><strong>理解区域：</strong>每个题目包含"我的理解/疑问："字段供填写</li>
                        <li><strong>题目解释：</strong>保留原始题目解释内容</li>
                    </ul>
                </div>

                <div class="buttons">
                    <button class="btn-primary" onclick="exportMarkdown('all')">
                        📄 导出全部题目(Markdown)
                    </button>
                    <button class="btn-success" onclick="exportMarkdown('unanswered')">
                        ❓ 导出未作答题目(Markdown)
                    </button>
                    <button class="btn-danger" onclick="exportMarkdown('wrong')">
                        ❌ 导出错误题目(Markdown)
                    </button>
                    <button class="btn-warning" onclick="exportMarkdown('missing_unanswered')">
                        ⚠️ 导出题干缺失且未作答(Markdown)
                    </button>
                    <button class="btn-danger" onclick="exportMarkdown('missing_wrong')" style="background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);">
                        🔴 导出题干缺失且回答错误(Markdown)
                    </button>
                </div>

                <!-- Markdown预览 -->
                <div class="input-group" style="margin-top: 20px;">
                    <label>Markdown预览（前3题）</label>
                    <textarea id="markdownPreview" readonly style="min-height: 200px; background-color: #f8f9fa;"></textarea>
                </div>

                <div id="markdownStatus" class="output hidden"></div>
                <div id="markdownDownloadLinks" class="file-list"></div>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script>
        let processedData = [];
        let originalData = [];

        // 文件拖拽功能
        document.addEventListener('DOMContentLoaded', function() {
            const fileUpload = document.querySelector('.file-upload');
            
            fileUpload.addEventListener('dragover', (e) => {
                e.preventDefault();
                fileUpload.querySelector('.file-upload-label').style.backgroundColor = '#f0f0ff';
            });

            fileUpload.addEventListener('dragleave', () => {
                fileUpload.querySelector('.file-upload-label').style.backgroundColor = '';
            });

            fileUpload.addEventListener('drop', (e) => {
                e.preventDefault();
                fileUpload.querySelector('.file-upload-label').style.backgroundColor = '';
                const files = e.dataTransfer.files;
                if (files.length > 0) {
                    document.getElementById('fileInput').files = files;
                }
            });
        });

        // 加载数据
        async function loadData() {
            const loadBtnText = document.getElementById('loadBtnText');
            const loadSpinner = document.getElementById('loadSpinner');
            const status = document.getElementById('loadStatus');
            
            try {
                loadBtnText.textContent = '加载中...';
                loadSpinner.classList.remove('hidden');
                status.className = 'output info';
                status.textContent = '正在处理数据...';
                status.classList.remove('hidden');

                let data = [];
                const csvInput = document.getElementById('csvInput').value.trim();
                const fileInput = document.getElementById('fileInput');

                if (csvInput) {
                    data = parseCSV(csvInput);
                } else if (fileInput.files.length > 0) {
                    const file = fileInput.files[0];
                    if (file.name.endsWith('.csv')) {
                        const text = await readFileAsText(file);
                        data = parseCSV(text);
                    } else if (file.name.endsWith('.xlsx')) {
                        data = await parseXLSX(file);
                    } else {
                        throw new Error('不支持的文件格式');
                    }
                } else {
                    throw new Error('请选择输入数据');
                }

                if (data.length === 0) {
                    throw new Error('没有找到有效数据');
                }

                // 数据预处理
                console.log('开始处理数据，输入记录数:', data.length);
                
                originalData = [...data];
                processedData = preprocessData(data);
                console.log('预处理后记录数:', processedData.length);

                showDataStats(processedData);
                showDataPreview(processedData);
                
                status.className = 'output success';
                status.innerHTML = `✅ 数据加载完成！共处理 ${processedData.length} 条记录（原始数据 ${data.length} 行）`;
                
                document.getElementById('previewSection').classList.remove('hidden');
                document.getElementById('filterSection').classList.remove('hidden');

            } catch (error) {
                status.className = 'output error';
                status.textContent = `❌ 加载失败：${error.message}`;
                console.error(error);
            } finally {
                loadBtnText.textContent = '📊 加载数据';
                loadSpinner.classList.add('hidden');
            }
        }

        // CSV解析
        function parseCSV(text) {
            // 移除BOM标记
            text = text.replace(/^\uFEFF/, '');
            
            const lines = [];
            let currentLine = '';
            let inQuotes = false;
            
            for (let i = 0; i < text.length; i++) {
                const char = text[i];
                const nextChar = text[i + 1];
                
                if (char === '"') {
                    if (inQuotes && nextChar === '"') {
                        currentLine += '"';
                        i++;
                    } else {
                        inQuotes = !inQuotes;
                    }
                } else if (char === '\n' && !inQuotes) {
                    lines.push(currentLine);
                    currentLine = '';
                } else if (char === '\r' && !inQuotes) {
                    if (nextChar === '\n') {
                        lines.push(currentLine);
                        currentLine = '';
                        i++;
                    } else {
                        lines.push(currentLine);
                        currentLine = '';
                    }
                } else {
                    currentLine += char;
                }
            }
            
            if (currentLine.trim()) {
                lines.push(currentLine);
            }
            
            if (lines.length === 0) return [];

            const headers = parseCSVLine(lines[0]);
            const data = [];

            for (let i = 1; i < lines.length; i++) {
                const line = lines[i].trim();
                if (!line) continue;

                const values = parseCSVLine(line);
                
                // 确保values数量和headers匹配
                if (values.length >= headers.length) {
                    const row = {};
                    headers.forEach((header, index) => {
                        row[header] = values[index] || '';
                    });
                    
                    // 只添加有有效数据的记录
                if (row['题目描述'] && row['题目描述'].trim()) {
                    data.push(row);
                } else if (row['题目选项-1'] && row['题目选项-1'].trim()) {
                    data.push(row);
                } else if (row['回答情况'] && row['回答情况'].trim()) {
                    data.push(row);
                }
                }
            }

            console.log('CSV解析完成: 表头数量=', headers.length, '数据记录数=', data.length);
            return data;
        }

        // 解析单行CSV
        function parseCSVLine(line) {
            const values = [];
            let current = '';
            let inQuotes = false;
            
            for (let i = 0; i < line.length; i++) {
                const char = line[i];
                const nextChar = line[i + 1];
                
                if (char === '"') {
                    if (inQuotes && nextChar === '"') {
                        current += '"';
                        i++;
                    } else {
                        inQuotes = !inQuotes;
                    }
                } else if (char === ',' && !inQuotes) {
                    values.push(current.trim());
                    current = '';
                } else {
                    current += char;
                }
            }
            
            values.push(current.trim());
            return values;
        }

        // XLSX解析
        async function parseXLSX(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    try {
                        const data = new Uint8Array(e.target.result);
                        const workbook = XLSX.read(data, { type: 'array' });
                        const sheetName = workbook.SheetNames[0];
                        const worksheet = workbook.Sheets[sheetName];
                        const json = XLSX.utils.sheet_to_json(worksheet);
                        resolve(json);
                    } catch (error) {
                        reject(error);
                    }
                };
                reader.onerror = () => reject(new Error('文件读取失败'));
                reader.readAsArrayBuffer(file);
            });
        }

        // 读取文件内容
        function readFileAsText(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = e => resolve(e.target.result);
                reader.onerror = () => reject(new Error('文件读取失败'));
                reader.readAsText(file, 'UTF-8');
            });
        }

        // 数据预处理
        function preprocessData(data) {
            const processed = [];
            let currentRecord = null;
            let recordCount = 0;
            
            console.log('原始数据行数:', data.length);
            
            for (let i = 0; i < data.length; i++) {
                const row = data[i];
                
                // 检查是否是有效记录（基于题目内容判断）
                const hasQuestionDesc = row['题目描述'] && row['题目描述'].trim();
                const hasQuestionOptions = row['题目选项-1'] && row['题目选项-1'].trim();
                const hasAnswerStatus = row['回答情况'] && row['回答情况'].trim();
                
                // 如果题目描述、选项或回答情况有内容，则视为有效记录
                const isValidRecord = hasQuestionDesc || hasQuestionOptions || hasAnswerStatus;
                
                if (isValidRecord) {
                    // 构建当前行的题目唯一标识
                    const currentQuestionKey = [
                        row['题目描述'] || '',
                        row['题目选项-1'] || '',
                        row['题目选项-2'] || '',
                        row['题目选项-3'] || '',
                        row['题目选项-4'] || ''
                    ].join('\t');
                    
                    // 构建当前记录的题目唯一标识（如果有）
                    const currentRecordQuestionKey = currentRecord ? [
                        currentRecord['题目描述'] || '',
                        currentRecord['题目选项-1'] || '',
                        currentRecord['题目选项-2'] || '',
                        currentRecord['题目选项-3'] || '',
                        currentRecord['题目选项-4'] || ''
                    ].join('\t') : null;
                    
                    // 如果当前有记录在处理，且题目内容不同，先保存当前记录
                    if (currentRecord && currentRecordQuestionKey !== currentQuestionKey) {
                        processed.push(currentRecord);
                        recordCount++;
                        currentRecord = null;
                    }
                    
                    // 开始新记录或合并数据
                    if (!currentRecord) {
                        currentRecord = { ...row };
                    } else {
                        // 合并题目解释等多行内容
                        if (row['题目解释'] && row['题目解释'].trim()) {
                            currentRecord['题目解释'] = (currentRecord['题目解释'] || '') + 
                                '\n' + row['题目解释'].trim();
                        }
                        // 合并题目描述（如果有）
                        if (row['题目描述'] && row['题目描述'].trim()) {
                            currentRecord['题目描述'] = (currentRecord['题目描述'] || '') + 
                                '\n' + row['题目描述'].trim();
                        }
                        // 合并其他字段（如果有）
                        if (row['回答情况'] && row['回答情况'].trim()) {
                            currentRecord['回答情况'] = row['回答情况'].trim();
                        }
                        if (row['正确答案'] && row['正确答案'].trim()) {
                            currentRecord['正确答案'] = row['正确答案'].trim();
                        }
                        if (row['你的答案'] && row['你的答案'].trim()) {
                            currentRecord['你的答案'] = row['你的答案'].trim();
                        }
                    }
                }
            }
            
            // 添加最后一条记录
            if (currentRecord) {
                processed.push(currentRecord);
                recordCount++;
            }
            
            console.log('处理后记录数:', recordCount);
            
            // 清理和标准化数据，同时移除不需要的列
            const cleanedRecords = processed.map(record => {
                const cleaned = {};
                Object.keys(record).forEach(key => {
                    // 移除web-scraper-order和web-scraper-start-url列
                    if (key === 'web-scraper-order' || key === 'web-scraper-start-url') {
                        return;
                    }
                    
                    if (record[key] && record[key].trim()) {
                        cleaned[key] = record[key].trim();
                    } else {
                        cleaned[key] = '';
                    }
                });
                return cleaned;
            });
            
            // 按题目内容进行去重
            const uniqueRecords = [];
            const seenQuestions = new Set();
            
            for (const record of cleanedRecords) {
                // 构建题目唯一标识：题目描述+四个选项
                const questionKey = [
                    record['题目描述'] || '',
                    record['题目选项-1'] || '',
                    record['题目选项-2'] || '',
                    record['题目选项-3'] || '',
                    record['题目选项-4'] || ''
                ].join('\t');
                
                // 如果题目内容完全相同，则跳过
                if (questionKey && seenQuestions.has(questionKey)) {
                    console.log('发现重复题目，跳过:', questionKey.substring(0, 50) + '...');
                    continue;
                }
                
                if (questionKey) {
                    seenQuestions.add(questionKey);
                }
                uniqueRecords.push(record);
            }
            
            console.log('去重后记录数:', uniqueRecords.length);
            return uniqueRecords;
        }

        // 显示数据统计
        function showDataStats(data) {
            const stats = document.getElementById('dataStats');
            
            const totalRecords = data.length;
            
            // 精确统计：确保各项之和等于总数
            const answeredRecords = data.filter(item => 
                item['回答情况'] && 
                item['回答情况'].trim() !== '' && 
                item['回答情况'] !== '未作答'
            );
            
            const unansweredRecords = data.filter(item => 
                !item['回答情况'] || 
                item['回答情况'].trim() === '' || 
                item['回答情况'] === '未作答'
            ).length;
            
            const wrongRecords = answeredRecords.filter(item => 
                item['回答情况'] === '回答错误'
            ).length;
            
            const correctRecords = answeredRecords.filter(item => 
                item['回答情况'] === '回答正确'
            ).length;
            
            const missingQuestionRecords = data.filter(item => 
                !item['题目描述'] || !item['题目描述'].trim()
            ).length;
            
            // 验证统计一致性
            const calculatedTotal = unansweredRecords + wrongRecords + correctRecords;
            console.log(`统计验证: 总记录=${totalRecords}, 未作答=${unansweredRecords}, 错误=${wrongRecords}, 正确=${correctRecords}, 计算总和=${calculatedTotal}`);
            
            const hasDescriptionRecords = data.filter(item => 
                item['题目描述'] && item['题目描述'].trim() !== ''
            ).length;
            
            const noDescriptionRecords = data.filter(item => 
                !item['题目描述'] || item['题目描述'].trim() === ''
            ).length;

            stats.innerHTML = `
                <div class="stat-card">
                    <div class="stat-number">${totalRecords}</div>
                    <div class="stat-label">总记录数</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number">${unansweredRecords}</div>
                    <div class="stat-label">未作答题目</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number">${wrongRecords}</div>
                    <div class="stat-label">回答错误题目</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number">${correctRecords}</div>
                    <div class="stat-label">回答正确题目</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number">${hasDescriptionRecords}</div>
                    <div class="stat-label">有题目描述</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number">${noDescriptionRecords}</div>
                    <div class="stat-label">无题目描述</div>
                </div>
            `;

            // 更新实时筛选预览
            updateLiveStats(totalRecords, unansweredRecords, wrongRecords, correctRecords, missingQuestionRecords);
        }

        // 更新实时筛选预览
        function updateLiveStats(total, unanswered, wrong, correct, missing) {
            const liveStatsDiv = document.getElementById('liveStats');
            if (!liveStatsDiv) return;

            // 根据新规范计算实时统计
            const actualUnanswered = processedData.filter(item => 
                item['题目描述'] && item['题目描述'].trim() !== '' &&
                (item['回答情况'] === '未作答' || item['回答情况'] === '未回答')
            ).length;

            const actualWrong = processedData.filter(item => 
                item['题目描述'] && item['题目描述'].trim() !== '' &&
                (item['回答情况'] === '回答错误' || item['回答情况'] === '错误')
            ).length;

            const actualMissingUnanswered = processedData.filter(item => 
                (!item['题目描述'] || item['题目描述'].trim() === '') &&
                (item['回答情况'] === '未作答' || item['回答情况'] === '未回答')
            ).length;

            const actualMissingWrong = processedData.filter(item => 
                (!item['题目描述'] || item['题目描述'].trim() === '') &&
                (item['回答情况'] === '回答错误' || item['回答情况'] === '错误')
            ).length;

            liveStatsDiv.innerHTML = `
                <div style="padding: 10px; background: white; border-radius: 6px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); min-width: 120px; text-align: center;">
                    <div style="font-size: 1.5em; font-weight: bold; color: #667eea;">${actualUnanswered}</div>
                    <div style="font-size: 0.8em; color: #666;">未作答(可筛选)</div>
                </div>
                <div style="padding: 10px; background: white; border-radius: 6px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); min-width: 120px; text-align: center;">
                    <div style="font-size: 1.5em; font-weight: bold; color: #e74c3c;">${actualWrong}</div>
                    <div style="font-size: 0.8em; color: #666;">错误(可筛选)</div>
                </div>
                <div style="padding: 10px; background: white; border-radius: 6px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); min-width: 120px; text-align: center;">
                    <div style="font-size: 1.5em; font-weight: bold; color: #f39c12;">${actualMissingUnanswered}</div>
                    <div style="font-size: 0.8em; color: #666;">缺失且未作答</div>
                </div>
                <div style="padding: 10px; background: white; border-radius: 6px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); min-width: 120px; text-align: center;">
                    <div style="font-size: 1.5em; font-weight: bold; color: #c0392b;">${actualMissingWrong}</div>
                    <div style="font-size: 0.8em; color: #666;">缺失且错误</div>
                </div>
                <div style="padding: 10px; background: white; border-radius: 6px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); min-width: 120px; text-align: center;">
                    <div style="font-size: 1.5em; font-weight: bold; color: #2ecc71;">${correct}</div>
                    <div style="font-size: 0.8em; color: #666;">回答正确</div>
                </div>
            `;
        }

        // 显示数据预览
        function showDataPreview(data) {
            const preview = document.getElementById('dataPreview');
            if (data.length === 0) {
                preview.innerHTML = '<p>没有数据可预览</p>';
                return;
            }

            const headers = Object.keys(data[0]);
            const previewData = data.slice(0, 5); // 显示前5条

            let html = '<table class="preview-table"><thead><tr>';
            headers.forEach(header => {
                html += `<th>${header}</th>`;
            });
            html += '</tr></thead><tbody>';

            previewData.forEach(row => {
                html += '<tr>';
                headers.forEach(header => {
                    const value = row[header] || '';
                    const displayValue = value.length > 50 ? value.substring(0, 50) + '...' : value;
                    html += `<td title="${value}">${displayValue}</td>`;
                });
                html += '</tr>';
            });

            html += '</tbody></table>';
            if (data.length > 5) {
                html += `<p><small>显示前5条，共${data.length}条记录</small></p>`;
            }

            preview.innerHTML = html;
            
            // 同时更新Markdown预览
            updateMarkdownPreview(data);
        }

        // 更新Markdown预览
        function updateMarkdownPreview(data) {
            const preview = document.getElementById('markdownPreview');
            if (data.length === 0) {
                preview.value = '没有数据可预览';
                return;
            }

            const previewData = data.slice(0, 3); // 显示前3题
            const markdown = convertToMarkdown(previewData);
            preview.value = markdown;
            
            // 显示Markdown导出区域
            document.getElementById('markdownSection').classList.remove('hidden');
        }

        // 数据筛选
        function filterData(type) {
            const customFilename = document.getElementById('customFilename').value.trim();
            const status = document.getElementById('filterStatus');
            const downloadLinks = document.getElementById('downloadLinks');

            let filteredData = [];
            let filename = '';

            try {
                switch (type) {
                    case 'unanswered':
                        filteredData = processedData.filter(row => 
                            row['题目描述'] && row['题目描述'].trim() !== '' &&
                            (row['回答情况'] === '未作答' || row['回答情况'] === '未回答')
                        );
                        filename = customFilename || '未作答题目.csv';
                        break;

                    case 'wrong':
                        filteredData = processedData.filter(row => 
                            row['题目描述'] && row['题目描述'].trim() !== '' &&
                            (row['回答情况'] === '回答错误' || row['回答情况'] === '错误')
                        );
                        filename = customFilename || '错误题目.csv';
                        break;

                    case 'missing_unanswered':
                        filteredData = processedData.filter(row => 
                            (!row['题目描述'] || row['题目描述'].trim() === '') &&
                            (row['回答情况'] === '未作答' || row['回答情况'] === '未回答')
                        );
                        filename = customFilename || '干缺失且未作答.csv';
                        break;

                    case 'missing_wrong':
                        filteredData = processedData.filter(row => 
                            (!row['题目描述'] || row['题目描述'].trim() === '') &&
                            (row['回答情况'] === '回答错误' || row['回答情况'] === '错误')
                        );
                        filename = customFilename || '干缺失且回答错误.csv';
                        break;
                }

                if (filteredData.length === 0) {
                    status.className = 'output info';
                    status.textContent = `没有找到符合条件的记录`;
                    return;
                }

                // 生成CSV文件
                const csv = convertToCSV(filteredData);
                const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
                const url = URL.createObjectURL(blob);

                // 创建下载链接
                const link = document.createElement('a');
                link.href = url;
                link.download = filename;
                link.innerHTML = `📥 ${filename} (${filteredData.length}条记录)`;

                downloadLinks.innerHTML = '';
                downloadLinks.appendChild(link);

                status.className = 'output success';
                status.innerHTML = `✅ 筛选完成！找到 ${filteredData.length} 条记录`;

                // 自动触发下载
                link.click();

            } catch (error) {
                status.className = 'output error';
                status.textContent = `❌ 筛选失败：${error.message}`;
                console.error(error);
            }
        }

        // 转换为CSV
        function convertToCSV(data) {
            if (data.length === 0) return '';

            const headers = Object.keys(data[0]);
            const csvRows = [headers.join(',')];

            data.forEach(row => {
                const values = headers.map(header => {
                    const value = row[header] || '';
                    // 处理包含逗号或引号的值
                    if (value.includes(',') || value.includes('"') || value.includes('\n')) {
                        return `"${value.replace(/"/g, '""')}"`;
                    }
                    return value;
                });
                csvRows.push(values.join(','));
            });

            return csvRows.join('\n');
        }

        // 转换为Markdown格式
        function convertToMarkdown(data) {
            if (data.length === 0) return '';

            let markdown = '';
            
            data.forEach((row, index) => {
                // 题目标题
                const title = row['题目描述'] || `题目 ${index + 1}`;
                markdown += `### ${title}\n\n`;
                
                // 选项列表
                const options = [];
                for (let i = 1; i <= 4; i++) {
                    const option = row[`题目选项-${i}`] || row[`选项${i}`] || '';
                    if (option.trim()) {
                        options.push(option.trim());
                    }
                }
                
                options.forEach(option => {
                    markdown += `- ${option}\n`;
                });
                
                if (options.length > 0) {
                    markdown += '\n';
                }
                
                // 答题信息区块
                const answerStatus = row['回答情况'] || '未知';
                const correctAnswer = row['正确答案'] || '未知';
                const userAnswer = row['你的答案'] || '未知';
                
                markdown += `回答情况：${answerStatus}\n`;
                markdown += `正确答案：${correctAnswer}\n`;
                markdown += `你的答案：${userAnswer}\n`;
                markdown += `我的理解/疑问：\n\n`;
                
                // 题目解释
                const explanation = row['题目解释'] || row['解析'] || '';
                if (explanation.trim()) {
                    markdown += `**题目解释：**\n${explanation.trim()}\n\n`;
                }
                
                // 题目分隔符
                if (index < data.length - 1) {
                    markdown += '========\n\n';
                }
            });
            
            return markdown;
        }

        // 获取与CSV筛选相同的数据
        function getFilteredDataForMarkdown(type) {
            switch (type) {
                case 'all':
                    return processedData;
                    
                case 'unanswered':
                    return processedData.filter(row => 
                        row['题目描述'] && row['题目描述'].trim() !== '' &&
                        (row['回答情况'] === '未作答' || row['回答情况'] === '未回答')
                    );
                    
                case 'wrong':
                    return processedData.filter(row => 
                        row['题目描述'] && row['题目描述'].trim() !== '' &&
                        (row['回答情况'] === '回答错误' || row['回答情况'] === '错误')
                    );
                    
                case 'missing_unanswered':
                    return processedData.filter(row => 
                        (!row['题目描述'] || row['题目描述'].trim() === '') &&
                        (row['回答情况'] === '未作答' || row['回答情况'] === '未回答')
                    );
                    
                case 'missing_wrong':
                    return processedData.filter(row => 
                        (!row['题目描述'] || row['题目描述'].trim() === '') &&
                        (row['回答情况'] === '回答错误' || row['回答情况'] === '错误')
                    );
                    
                default:
                    return processedData;
            }
        }

        // Markdown导出功能 - 与CSV筛选逻辑严格对应
        function exportMarkdown(type) {
            const status = document.getElementById('markdownStatus');
            const downloadLinks = document.getElementById('markdownDownloadLinks');

            try {
                // 获取与CSV筛选相同的数据
                const filteredData = getFilteredDataForMarkdown(type);
                
                if (filteredData.length === 0) {
                    status.className = 'output info';
                    status.textContent = `没有找到符合条件的记录`;
                    return;
                }

                // 生成对应的文件名
                let filename = '';
                switch (type) {
                    case 'all':
                        filename = '全部题目.md';
                        break;
                    case 'unanswered':
                        filename = '未作答题目.md';
                        break;
                    case 'wrong':
                        filename = '错误题目.md';
                        break;
                    case 'missing_unanswered':
                        filename = '干缺失且未作答.md';
                        break;
                    case 'missing_wrong':
                        filename = '干缺失且回答错误.md';
                        break;
                    default:
                        filename = '筛选结果.md';
                }

                // 生成Markdown文件
                const markdown = convertToMarkdown(filteredData);
                const blob = new Blob([markdown], { type: 'text/markdown;charset=utf-8;' });
                const url = URL.createObjectURL(blob);

                // 创建下载链接
                const link = document.createElement('a');
                link.href = url;
                link.download = filename;
                link.innerHTML = `📥 ${filename} (${filteredData.length}条记录)`;

                downloadLinks.innerHTML = '';
                downloadLinks.appendChild(link);

                status.className = 'output success';
                status.innerHTML = `✅ Markdown导出完成！找到 ${filteredData.length} 条记录`;

                // 自动触发下载
                link.click();

            } catch (error) {
                status.className = 'output error';
                status.textContent = `❌ Markdown导出失败：${error.message}`;
                console.error(error);
            }
        }

        // 清空数据
        function clearData() {
            document.getElementById('csvInput').value = '';
            document.getElementById('fileInput').value = '';
            document.getElementById('customFilename').value = '';
            document.getElementById('loadStatus').classList.add('hidden');
            document.getElementById('previewSection').classList.add('hidden');
            document.getElementById('filterSection').classList.add('hidden');
            document.getElementById('downloadLinks').innerHTML = '';
            document.getElementById('filterStatus').classList.add('hidden');
            processedData = [];
            originalData = [];
        }

        // 键盘快捷键
        document.addEventListener('keydown', function(e) {
            if (e.ctrlKey && e.key === 'Enter') {
                if (!document.getElementById('previewSection').classList.contains('hidden')) {
                    filterData('unanswered');
                } else {
                    loadData();
                }
            }
        });
    </script>
</body>
</html>